<template>
	<div class="system-user-dialog-container energy-from energy-dialog">
		<el-dialog center align-center v-model="state.dialog.isShowDialog" width="45%" @close="resetData">
			<template #header="{ titleClass }">
				<div :class="titleClass">{{ state.dialog.isAdd ? '新增用户' : '修改用户' }}</div>
			</template>
			<el-form ref="userDialogFormRef" :model="state.ruleForm" :rules="state.rules" size="default" label-width="90px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="昵称" prop="nickName">
							<el-input v-model="state.ruleForm.nickName" placeholder="请输入用户昵称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" v-if="state.dialog.isAdd">
						<el-form-item label="用户密码" prop="password">
							<el-input v-model="state.ruleForm.password" placeholder="请输入密码" type="password" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="用户性别" prop="sex">
							<el-select v-model="state.ruleForm.sex" placeholder="请选择性别" clearable class="w100">
								<el-option label="男" :value="1"></el-option>
								<el-option label="女" :value="0"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="手机号码" prop="phoneNumber">
							<el-input v-model="state.ruleForm.phoneNumber" placeholder="请输入手机号" clearable></el-input>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="用户类型">
							<el-radio-group v-model="state.ruleForm.userType">
								<el-radio :label="0"> <span class="font14">管理员 (不可删除)</span></el-radio>
								<el-radio :label="1"> <span class="font14">普通用户 (可删除)</span></el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="用户状态">
							<el-switch
								v-model="state.ruleForm.status"
								size="default"
								:active-value="0"
								:inactive-value="1"
								active-text="启用"
								inactive-text="禁用"
								inline-prompt
								style="--el-switch-on-color: #13ce66"
							/>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>

			<div class="flex row-center mt10 mb10">
				<div class="btn3" @click="onCancel">
					<el-icon> <ele-Close /> </el-icon><span class="ml6">取 消</span>
				</div>
				<div class="btn1 ml10" @click="onSubmit()">
					<el-icon> <ele-Check /> </el-icon><span class="ml6">保 存</span>
				</div>
			</div>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemUserDialog">
import { reactive, ref, nextTick } from 'vue';
import { useUserApi } from '/@/api/user/index';
import { ElNotification } from 'element-plus';
import JSEncrypt from 'jsencrypt';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const userDialogFormRef = ref();
const state: any = reactive({
	ruleForm: {
		id: '', // 用户id
		nickName: '', // 昵称
		sex: 1, // 性别
		phoneNumber: '', // 手机号
		password: '', // 账户密码
		userType: 1, // 用户类型（0管理员，1普通用户）
		status: 0, // 	用户状态（0正常 1停用）
	},
	dialog: {
		isShowDialog: false,
		isAdd: true,
	},
	rules: {
		nickName: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
		sex: [{ required: true, message: '请选择用户性别', trigger: 'blur' }],
		password: [{ required: true, message: '请输入用户密码', trigger: 'blur' }],
		phoneNumber: [
			{ required: true, message: '请输入用户手机号', trigger: 'blur' },
			{ pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' },
		],
	},
});

// 打开弹窗
const openDialog = async (row: any) => {
	if (row) {
		state.ruleForm = {
			id: row.id,
			nickName: row.nickName,
			sex: row.sex,
			phoneNumber: row.phoneNumber,
			password: row.password,
			userType: row.userType,
			status: row.status,
		};
		state.dialog.isAdd = false;
	} else {
		state.dialog.isAdd = true;
	}
	state.dialog.isShowDialog = true;
};

// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};

// 取消
const onCancel = () => {
	closeDialog();
};

// 表单清空
const resetData = () => {
	nextTick(() => {
		userDialogFormRef.value.resetFields();
		state.ruleForm = {
			id: '', // 用户id
			nickName: '', // 昵称
			sex: 1, // 性别
			phoneNumber: '', // 手机号
			password: '', // 账户密码
			userType: 1, // 用户类型（0管理员，1普通用户）
			status: 0, // 	用户状态（0正常 1停用）
		};
	});
};

// 新增用户
const doAddUser = async () => {
	const data = await useUserApi().addUser(state.ruleForm);
	if (data.code == 200) {
		ElNotification({
			title: '提示',
			message: '新增用户成功',
			position: 'top-right',
			type: 'success',
		});
		emit('refresh');
	}
};

// 编辑用户
const doEditUser = async () => {
	const data = await useUserApi().updateUser(state.ruleForm);
	if (data.code == 200) {
		ElNotification({
			title: '提示',
			message: '用户修改成功',
			position: 'top-right',
			type: 'success',
		});
		emit('refresh');
	}
};

// 提交
const onSubmit = () => {
	userDialogFormRef.value.validate((valid: any) => {
		if (valid) {
			if (state.ruleForm.password) {
				const crypt: any = new JSEncrypt();
				crypt.setKey(import.meta.env.VITE_PUBLIC_kEY);
				state.ruleForm.password = crypt.encrypt(state.ruleForm.password);
			}
			state.dialog.isAdd ? doAddUser() : doEditUser();
			closeDialog();
		} else {
			ElNotification({
				title: '提示',
				message: '校验失败,请填写完整用户信息',
				position: 'top-right',
				type: 'error',
			});
		}
	});
};

// 暴露变量
defineExpose({
	openDialog,
});
</script>
<style scoped lang="scss"></style>
